package com.zcsy.manage.owner.filter;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.owner.service.common.IOCommonTokenService;

/**
 * token拦截器
 * @Description: 
 * @author: zt
 * @date: 2016年6月27日
 * @version： v1.0 Copyright (c) 2014 Wuhan Hongyi Infomation Co., Ltd.
 */
public class UserHandlerInterceptor implements HandlerInterceptor{

	/** 拦截器白名单 */
	private static final List<String> whiteList = new ArrayList<String>();

	/** 登陆url */
	private static final String URL_LOGIN = "/user/userLogin";

	/** token过期url */
	private static final String URL_TOKEN_EXPIRE = "/user/tokenIsExpire";
	
	@Autowired
	private IOCommonTokenService commomTokenService;
	
	static {
		//添加白名单
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		// 转换参数,后期参数加密可能会用到
		// ParamsHttpServletRequestWrapper mParams = new
		// ParamsHttpServletRequestWrapper(request);

		final String uri = request.getRequestURI();
		final String loginResource = request.getContextPath() + URL_LOGIN;
		final String tokenExpireResource = request.getContextPath() + URL_TOKEN_EXPIRE;

		// 登陆和token异常方法跳过
		if (loginResource.equals(uri) || tokenExpireResource.equals(uri)) {
			return true;
		}

		// 白名单跳过
		if (!isWhiteUri(uri)) {

			// 获取token
			String token = request.getParameter("token");
			//判断token是否过期
			CommonToken tokenInfo = commomTokenService.selectByToken(token);
			
			//token被改变或token失效
			if(tokenInfo.getId() == null){
				int tokenMessage = tokenInfo.getTokenMessage();
				response.sendRedirect(request.getContextPath() + URL_TOKEN_EXPIRE + "?tokenMessage=" + tokenMessage);
				return false;
			}
			
			return true;
			

		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * 是白名单uri，不进行拦截
	 * 
	 * @param uri
	 * @return
	 * @author: zt
	 * @date: 2016年6月27日
	 */
	private boolean isWhiteUri(final String uri) {
		for (final String whiteUrl : whiteList) {
			if (uri.contains(whiteUrl)) {
				return true;
			}
		}
		return false;
	}

}
